Dictionaries

A Python dictionary is a mutable data structure that can be used to associate keys with values. They are created using {} braces. You can think of dictionaries as lists, except that instead of extracting elements by their position you extract them using their keys. One way of creating them follows.


In [1]:
numbers = {1: "one", 2: "two", 3: "three"}
numbers


Out[1]:
{1: 'one', 2: 'two', 3: 'three'}

In the numbers dictionary the keys are 1, 2 and 3 and their corresponding values are "one", "two" and "three". Extracting a value from a dictionary is very similar to extracting an element from a list.


In [2]:
numbers[2]


Out[2]:
'two'

Creating Dictionaries and Extracting Elements

The power of dictionary comes from the fact that keys don't have to be numbers. They can be any immutable data structure.


In [3]:
elements = {
    "H": "Hydrogen",
    "He": "Helium",
    "Li": "Lithium",
}
elements


Out[3]:
{'H': 'Hydrogen', 'He': 'Helium', 'Li': 'Lithium'}

In [4]:
elements["H"]


Out[4]:
'Hydrogen'

In [5]:
houses = {
    ("Harry", "Potter"): "Gryffindor",
    ("Hermione", "Granger"): "Gryffindor",
    ("Draco", "Malfoy"): "Slytherin",
    ("Cho", "Chang"): "Ravenclaw"
}
houses


Out[5]:
{('Cho', 'Chang'): 'Ravenclaw',
 ('Draco', 'Malfoy'): 'Slytherin',
 ('Harry', 'Potter'): 'Gryffindor',
 ('Hermione', 'Granger'): 'Gryffindor'}

In [6]:
houses[("Harry", "Potter")]


Out[6]:
'Gryffindor'

Adding and Removing Elements

Dictionaries are mutable so just like lists you can add and remove new mappings.


In [7]:
# Adding a mapping.
elements["Au"] = "Gold"
elements


Out[7]:
{'Au': 'Gold', 'H': 'Hydrogen', 'He': 'Helium', 'Li': 'Lithium'}

In [8]:
# Removing a mapping.
elements.pop("H")


Out[8]:
'Hydrogen'

In [9]:
elements


Out[9]:
{'Au': 'Gold', 'He': 'Helium', 'Li': 'Lithium'}

Much like with lists, attempting to access an element that doesn't exist will result in an error.


In [10]:
elements["Ag"]


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-10-c5571bb0bb35> in <module>()
----> 1 elements["Ag"]

KeyError: 'Ag'

It is possible to check if a key is in a dictionary.


In [11]:
("Harry", "Potter") in houses


Out[11]:
True

In [12]:
("Ronald", "Weasley") in houses


Out[12]:
False